import path from 'path';
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import { createMpaPlugin, createPages } from 'vite-plugin-virtual-mpa';
import qiankun from 'vite-plugin-qiankun'
import basicSsl from '@vitejs/plugin-basic-ssl'
var cheerio = require('cheerio');
const base = '/'; // You can change whatever you want
var createQiankunHelper = function (qiankunName) { return "\n  const createDeffer = (hookName) => {\n    const d = new Promise((resolve, reject) => {\n      window.proxy && (window.proxy[`vite${hookName}`] = resolve)\n    })\n    return props => d.then(fn => fn(props));\n  }\n  const bootstrap = createDeffer('bootstrap');\n  const mount = createDeffer('mount');\n  const unmount = createDeffer('unmount');\n  const update = createDeffer('update');\n\n  ;(global => {\n    global.qiankunName = '" + qiankunName + "';\n    global['" + qiankunName + "'] = {\n      bootstrap,\n      mount,\n      unmount,\n      update\n    };\n  })(window);\n"; };
const pages = createPages([
  {
    name: 'iframe',
    /**
     * filename is optional, default is `${name}.html`, which is the relative path of `build.outDir`.
     */
    filename: 'fruits/iframe.html', // output into sites/fruits/apple.html at build time.
    entry: '/src/pages/iframe/index.js',
    data: {
      title: 'This is iframe page',
    },
  },
  {
    name: 'apple',
    /**
     * filename is optional, default is `${name}.html`, which is the relative path of `build.outDir`.
     */
    filename: 'fruits/apple.html', // output into sites/fruits/apple.html at build time.
    entry: '/src/pages/apple/index.js',
    data: {
      title: 'This is Apple page',
    },
  },
  {
    name: 'home',
    filename: 'fruits/home.html',
    entry: '/src/pages/home/index.js',
    data: {
      title: 'This is Home page',
    },
  },
]);
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var cheerio__default = /*#__PURE__*/_interopDefaultLegacy(cheerio);

function __spreadArray(to, from) {
    for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
        to[j] = from[i];
    return to;
}
var module2DynamicImport = function ($, scriptTag) {
  if (!scriptTag) {
      return;
  }
  var script$ = $(scriptTag);
  var moduleSrc = script$.attr('src');
  var appendBase = '';
  appendBase = '(window.proxy ? (window.proxy.__INJECTED_PUBLIC_PATH_BY_QIANKUN__ + \'..\') : \'\') + ';
  script$.removeAttr('src');
  script$.removeAttr('type');
  script$.html("import(" + appendBase + "'" + moduleSrc + "')");
  return script$;
};
const myPlugin = () => ({
  name: 'configure-server',
  configureServer(server) {
    server.middlewares.use(function (req, res, next) {
      if(req.url.indexOf('iframe?') > -1 || req.url.indexOf('iframe.html') > -1) {
        var end = res.end.bind(res);
        res.end = function () {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                args[_i] = arguments[_i];
            }
            var htmlStr = args[0], rest = args.slice(1);
            if (typeof htmlStr === 'string') {
                var $ = cheerio__default['default'].load(htmlStr);
                module2DynamicImport($, $("script[src=" + base + "@vite/client]").get(0));
                htmlStr = $.html();
            }
            end.apply(void 0, __spreadArray([htmlStr], rest));
        }; 
      }
      next();
    });
  }
})

export default defineConfig(({ mode }) => {
  return {
    base,
    define: {
      IS_VITE: true,
      DEFINE_IS_NATIVE_DEV: false
    },
    plugins: [
      vue(),
      vueJsx(),
      basicSsl(),
      myPlugin(),
      qiankun('vite-plugin-virtual-mpa-demo', {
          useDevMode: true
        }),
      createMpaPlugin({
        template: 'src/template.html',
        pages,
      }),
    ],
    build: { sourcemap: true },
    server: { 
      port: 5173, 
      https: true,
      proxy: {
        '/iframe': {
          // 设置html代理
          target: 'https://localhost:5173/fruits/iframe.html',
          rewrite: (path) => path.replace(/^\/iframe/, ''),
          secure: false
        }
      }
    },
    optimizeDeps: { force: true },
    resolve: { alias: { '@': path.resolve('src') } },
  }
})
